/*
 * 创建日期 2009-12-14
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.grid.report;

import  org.fantasy.common.db.bean.ReportRow;
import  org.fantasy.common.db.bean.Row;
import  org.fantasy.common.grid.bean.Column;
import  org.fantasy.common.grid.bean.ReportParam;
import  org.fantasy.common.grid.custom.BaseCellCustom;
import  org.fantasy.common.grid.custom.CellCustom;
import  org.fantasy.common.grid.custom.RowCustom;
import  org.fantasy.common.util.Debug;
import  org.fantasy.common.util.StringUtil;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;

/**
 *  构造Excel
 * @author: 王文成
 * @version: 1.0
 * @since 2009-12-14
 */
public class POIExcelBuilder implements ReportBuilder {

    private static final Log log = LogFactory.getLog(POIExcelBuilder.class);

    protected ReportParam param;

    protected RowCustom rowCustom;

    protected CellCustom cellCustom;

    protected List<List<Column>> tableHeads;

    protected List<Column> tableFields;

    protected Set<String> hideHeads;

    protected List<ReportRow> resultList;
    
    private HSSFWorkbook workbook = new HSSFWorkbook();

    public POIExcelBuilder(ReportParam report) throws Exception {
        this.param = report;
        init();
    }

    /**
     * 初始化数据
     * 
     * @throws Exception
     */
    @SuppressWarnings("all")
    private void init() throws Exception {
        this.rowCustom = param.getRowCustom();
        this.cellCustom = new ExportCellCustom();
        this.tableHeads = param.getTableHeads();
        this.tableFields = param.getTableFields();
        this.hideHeads = param.getHideHeads();
        this.resultList = param.getDataList();
    }

    /**
     * 构建表头
     * 
     * @throws Exception
     */
    protected void buildHead(HSSFSheet sheet) throws Exception {
        HSSFCellStyle style = workbook.createCellStyle();
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        HSSFFont font = workbook.createFont();   
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(font);
        HSSFRow row = sheet.createRow(0);
        for (int i = 0 , k = 0 ; i < tableFields.size(); i++) {
            Column col = tableFields.get(i);
            if (param.isHideCol(col))
                continue;
            HSSFCell cell = row.createCell(k);k++;
            cell.setCellStyle(style);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue(col.getFieldLabel());
        }
    }
    

    /**
     * 构建表体
     * 
     * @throws Exception
     */
    protected StringBuffer buildBody(HSSFSheet sheet) throws Exception {
        StringBuffer html = new StringBuffer(1024);
        int start = 1;
        for (int i = 0; i < resultList.size(); i++) {
            ReportRow data = resultList.get(i);
            HSSFRow row = sheet.createRow(start + i);
            buildCells(data, row);
        }
        return html;
    }

    /**
     * 构造一行中的所有列
     * 
     * @return
     */
    protected void buildCells(ReportRow data, HSSFRow row) throws Exception {
        for (int i = 0 , k = 0 ; i < tableFields.size(); i++) {
            Column col = tableFields.get(i);
            if (param.isHideCol(col))
                continue;

            String value = cellCustom.getValue(data, col);
            HSSFCell cell = row.createCell(k);k++;
            if (col.isNumberType()) {
                cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                if( StringUtil.isValid(value) ){
                    cell.setCellValue( new Double(value) );
                }else{
                    cell.setCellValue( 0 );
                }
            } else {
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellValue(value);
            }
        }
    }
    
    public Object getReport() throws Exception {
        HSSFSheet sheet = workbook.createSheet(param.getExportName());
        Debug debug = new Debug("Report");
        debug.start("Building Report");
        this.buildHead(sheet);
        this.buildBody(sheet);
        debug.end("Building Report");
        log.info(debug);
        return workbook;
    }

    private static class ExportCellCustom extends BaseCellCustom {

        @Override
        public String getValue(Row row, Column col) throws Exception {
            String value = null;
            // 如果是表达式
            if (col.isExpressionType()) {
                BigDecimal fieldValue = eval(col.getExpression(), row, col.getExpParams());
                int scale = col.isPercentType() ? 4 : 2;
                BigDecimal decimal = fieldValue.setScale(col.getScale(scale), BigDecimal.ROUND_HALF_UP);
                value = String.valueOf(decimal);
            } else {
                value = row.getCell(col.getFieldName()).getString();
            }
            return value;
        }

    }

    public static void main(String[] args) {

    }
}
